<script setup>
import { ref, onMounted } from 'vue'
import Message from '@arco-design/web-vue/es/message'
import CodeEditor from '@/components/CodeEditor.vue'
import MdViewer from '@/components/MdViewer.vue'
import { getQuestionDetailById, submitQuestion } from '@/api/question.js'
import TitleComponent from '@/components/TitleComponent.vue'
import router from '@/router/index.js'

const question = ref({
  id: '',
  title: '',
  content: '',
  tags: [],
  passFlag: false,
  answer: '',
  prompt: [
    { language: 'java', codePrompt: '请输入java代码' }
  ],
  judgeConfig: {},
})
const form = ref({
  language: 'java',
  code: '',
  questionId: ''
})

const getQuestionInfo = () => {
  const questionId = router.currentRoute.value.params.id
  if (!questionId) {
    Message.error('题目id不能为空')
    router.back()
    return
  }
  getQuestionDetailById(questionId)
    .then(res => {
      if (res.data.code === 1) {
        question.value = res.data.data
        form.value.questionId = question.value.id
        // 初始化代码提示
        const defaultPrompt = question.value.prompt.find(p => p.language === form.value.language)
        if (defaultPrompt) {
          form.value.code = defaultPrompt.codePrompt
        }
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('获取题目详情失败')
    })
}

const submitLoading = ref(false)

const submitForm = () => {
  if (!validateForm()) {
    return
  }
  submitLoading.value = true
  submitQuestion(form.value)
    .then(res => {
      if (res.data.code === 1) {
        Message.success('提交成功')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('提交失败')
    })
    .finally(() => {
      submitLoading.value = false
    })
}

const validateForm = () => {
  // 验证表单
  if (form.value.code === '') {
    Message.error('请输入代码')
    return false
  }
  if (form.value.code.length > 2000) {
    Message.error('代码量不能超过2000字符')
    return false
  }
  if (form.value.language === '') {
    Message.error('请选择编程语言')
    return false
  }
  if (form.value.questionId === '') {
    Message.error('题目id不能为空')
    return false
  }
  return true
}

const changeCode = (value) => {
  form.value.code = value
}

const codeEditorRef = ref()

const handleLanguageChange = (newLanguage) => {
  const selectedPrompt = question.value.prompt.find(p => p.language === newLanguage)
  if (selectedPrompt) {
    form.value.code = selectedPrompt.codePrompt
  } else {
    form.value.code = ''
  }
  codeEditorRef.value.resetEditorState()
}

onMounted(() => {
  getQuestionInfo()
})
</script>

<template>
  <div id="viewQuestionView">
    <a-spin :loading="submitLoading" tip="提交中..." style="width: 100%">
      <a-card class="card">
        <title-component :title-text="question.title" />
        <a-row :gutter="[24, 24]">
          <a-col :md="12" :xs="24">
            <a-tabs default-active-key="question">
              <a-tab-pane key="question" title="题目">
                <a-card v-if="question" :title="question.title">
                  <a-descriptions
                    title="判题条件"
                    :column="{ xs: 1, md: 2, lg: 3 }"
                  >
                    <a-descriptions-item label="时间限制">
                      {{ question.judgeConfig.timeLimit ?? 0 }} ms
                    </a-descriptions-item>
                    <a-descriptions-item label="内存限制">
                      {{ question.judgeConfig.memoryLimit ?? 0 }} B
                    </a-descriptions-item>
                    <a-descriptions-item label="堆栈限制">
                      {{ question.judgeConfig.stackLimit ?? 0 }} B
                    </a-descriptions-item>
                  </a-descriptions>
                  <MdViewer :value="question.content || ''" />
                  <template #extra>
                    <a-space wrap>
                      <a-tag
                        v-for="(tag, index) in question.tags"
                        :key="index"
                        color="blue"
                      >{{ tag }}
                      </a-tag>
                    </a-space>
                  </template>
                </a-card>
              </a-tab-pane>
              <a-tab-pane key="answer" title="答案">
                <MdViewer v-if="question.passFlag" :value="question.answer || ''" />
                <a-empty v-else description="未通过题目，无法查看答案"/>
              </a-tab-pane>
            </a-tabs>
          </a-col>
          <a-col :md="12" :xs="24">
            <a-form :model="form" layout="inline" @submit="submitForm">
              <a-form-item
                field="language"
                label="编程语言"
                style="min-width: 240px"
              >
                <a-select
                  v-model="form.language"
                  placeholder="选择编程语言"
                  @change="handleLanguageChange"
                >
                  <a-option v-for="prompt in question.prompt" :key="prompt.language"
                            :value="prompt.language">
                    {{ prompt.language }}
                  </a-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit" :loading="submitLoading">
                  提交代码
                </a-button>
              </a-form-item>
            </a-form>
            <CodeEditor
              ref="codeEditorRef"
              :value="form.code"
              :language="form.language"
              :handle-change="changeCode"
            />
            <a-divider size="0" />
          </a-col>
        </a-row>
      </a-card>
    </a-spin>
  </div>
</template>

<style>
.card {
  margin-top: 20px;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}
</style>
